﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Windows;
using System.Xml.Serialization;

namespace CoverFlow.Client.Models
{
    public class DataModel
    {
        public void GetTrailers(Action<IEnumerable<Trailer>, Exception> callback)
        {
            var client = new WebClient();
            client.OpenReadCompleted += (s, e) =>
            {
                var userCallback = e.UserState as Action<IEnumerable<Trailer>, Exception>;
                if (userCallback != null)
                {
                    if (e.Error != null)
                        userCallback(null, e.Error);
                    else
                    {
                        try
                        {
                            var data = new byte[e.Result.Length];
                            e.Result.Read(data, 0, data.Length);

                            var serializer = new XmlSerializer(typeof(MovieTrailers));
                            string xml = System.Text.Encoding.UTF8.GetString(data, 0, data.Length);
                            TextReader r = new StringReader(xml);
                            var movieTrailers = (MovieTrailers)serializer.Deserialize(r);
                            userCallback(movieTrailers.Trailers, null);
                        }
                        catch (Exception ex)
                        {
                            userCallback(null, ex);
                        }

                    }

                }
            };
            var uri = new Uri(Application.Current.Host.Source, "../trailers");
            client.OpenReadAsync(uri, callback);
        }
    }
}
